<?php
!defined('IN_APP') && exit('Access Denied');

class User {
	private $uid;
	private $fields;
	private static $name = 'users';
	public function __construct() {
		$this-> uid = null;
		$this-> fields = array(
			'account' => '',
			'password' => '',
			'nickname' => '',
			'lastloginip' => '',
			'lastlogintime' => '',
			'logintimes' => 0,
			'postcount' => 0);
	}
	
	public function __get($field) {
		if ($field == 'userId') {
			return $this->uid;
		} else {
			return array_key_exists($field, $this->fields) ?
			    $this->fields[$field] : '';		
		}
	}
	
	public function __set($field, $value) {
		if (array_key_exists($field, $this->fields)) {
			$this->fields[$field] = value;
		}
	}
	
	public function setId($value) {
		$this->uid = $value;	
	}
	
	public function setAccount($value) {
		$this->fields['account'] = $value;
	}
	
	public function setPassword($value, $needHash = false) {
		$this->fields['password'] = $needHash ? sha1($value) : $value;
	}
	
	public function setNickname($value) {
		$this->fields['nickname'] = $value;
	}
	
	public function setLastIp($value) {
		$this->fields['lastloginip'] = $value;
	}
	
	public function setLastLoginTime($value) {
		$this->fields['lastlogintime'] = $value;
	}
	
	public function setLoginTimes($value) {
		$this->fields['logintimes'] = $value;
	}
	
	public function setPostCount($value) {
		$this->fields['postcount'] = $value;
	}
	
	public function Load(array $row, $needHash = false) {
		array_key_exists('id',$row) && $this->setId($row['id']);
		array_key_exists('user_name', $row) && $this->setAccount($row['user_name']);
		array_key_exists('user_pass', $row) && $this->setPassword($row['user_pass'], $needHash);
		array_key_exists('nickname', $row) && $this->setNickname($row['nickname']);
		array_key_exists('lastloginip', $row) && $this->setLastIp($row['lastloginip']);
		array_key_exists('lastlogintime', $row) && $this->setLastLoginTime($row['lastlogintime']);
		array_key_exists('logintimes', $row) && $this->setLoginTimes($row['logintimes']);
		array_key_exists('postcount', $row) && $this->setPostCount($row['postcount']);
	}
	
	/**
	 * 
	 * 验证用户名是否符合规范
	 * @param string $account
	 * @return 符合规范返回true, 否则返回 false
	 */
	public static function validateAccount($account) {
		return preg_match('/^[a-zA-Z]{3, 20}$/i', $account);
	}
	
	/**
	 * 
	 * 验证是否合法的Email
	 * @param string $email
	 * @return Email合法返回true，否则返回false
	 */
	public static function validateEmail($email) {
		return filter_var($email, FILTER_VALIDATE_EMAIL);
	}
	
	public static function getById($uid) {
		global $db, $tablepre;
		$user = new User();
		$query = sprintf('SELECT DISTINCT id, user_name, user_pass, nickname, lastloginip, lastlogintime, logintimes, postcount '.
		                 'FROM %s%s WHERE id = %d', $tablepre, self::$name, $uid);
		$result = $db->fetch_first($query);
		$result && $user->Load($result);
		return $user;
	}
	
	public static function getByName($uname) {
		global $db, $tablepre;
		$user = new User();
		$query = sprintf('SELECT DISTINCT id, user_name, user_pass, nickname, lastloginip, lastlogintime, logintimes, postcount '.
		                 'FROM %s%s WHERE user_name = "%s"', $tablepre, self::$name, mysql_real_escape_string($uname));
		$result = $db->fetch_first($query);
		$result && $user->Load($result);
		return $user;
	}

	public function save() {
		global $db, $tablepre;
		$query = '';
		if ($this->uid) {
			$query = 'UPDATE %s%s SET user_name = "%s", ' .
			         'user_pass = "%s", nickname = "%s", lastloginip = "%s", '.
			         'lastlogintime = %d, logintimes = %d, postcount = %d '.
			         'WHERE id = ' . $this->uid;
		} else {
			$query = 'INSERT INTO %s%s (user_name, user_pass, nickname, lastloginip, lastlogintime, logintimes, postcount) ' .
			         'VALUES("%s", "%s", "%s", "%s", %d, %d, %d)';
		}
		$query = sprintf($query, $tablepre, self::$name,
			         mysql_real_escape_string($this->account),
			         mysql_real_escape_string($this->password),
			         mysql_real_escape_string($this->nickname),
			         mysql_real_escape_string($this->lastloginip),
			         $this->lastlogintime, $this->logintimes, $this->postcount);
	   if ($this->uid) {
	   		return $db->query($query);
	   } else {
	   		if ($db->query($query)) {
	   			$this->uid = $db->insert_id();
	   			return true;
	   		} else {
	   			return false;
	   		}
	   }
	}
	
	public static function UserLogin($account, $pass) {
		$result = array(
			'logined' => 'false',
			'user' => NULL,
		    'message' => '登录失败，发生未知错误，请稍候重试'
		);
		
		$user = self::getByName($account);
		if ($user->uid) {
			if (sha1($pass) == $user->password) {
				$result['logined'] = true;
				$result['user'] = $user;
				$result['message'] = '登录成功';
			} else {
				$result['message'] = '密码错误';
			}
		} else {
			$result['message'] = "用户名{$account}不存在";
		}
		return $result;
	}
}